package com.zry.simpleBlog.comment.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * MD5 工具类 用来对密码的二次加密
 * <p>
 * 示例可用的
 * 用户名：root
 * 密码：b5fb686c5752edd1c337ac7231c6cea5 -> root
 *
 */
public class MD5Util {
    private static String salt = "1a2b3c4d";

    public static String md5(String src) {
        return DigestUtils.md5DigestAsHex(src.getBytes(StandardCharsets.UTF_8));
    }

    public static String inputPassToFromPass(String inputPass) {
        String str = "" + salt.charAt(0) + salt.charAt(2) + inputPass + salt.charAt(5) + salt.charAt(4);
        return md5(str);
    }

    public static String formPassToDBPass(String formPass, String salt) {
        String str = "" + salt.charAt(0) + salt.charAt(2) + formPass + salt.charAt(5) + salt.charAt(4);
        return md5(str);
    }

    // 我们需要调用的方法   返回二次加密后的密码
    public static String inputPassToDBPass(String inputPass, String salt) {
        String fromPass = inputPassToFromPass(inputPass);
        String dbPass = formPassToDBPass(fromPass, salt);
        return dbPass;
    }

    /**
     * 功能描述: 生成密码
     *
     * @create 2022/5/16
     */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的明文密码");
        String password = scanner.nextLine().trim();
        if (ObjectUtils.isEmpty(password) || password.length() < 5) {
            System.out.println("密码要符合格式");
            return;
        }
        System.out.println("你明文密码是：" + password);
        String first = MD5Util.inputPassToFromPass(password);
        String second = MD5Util.formPassToDBPass(first, salt);
//        b5fb686c5752edd1c337ac7231c6cea5
        System.out.println();
        //85779e93f9bd754d8b2f66cca44a0ab6
        System.out.println("第一次加密之后：" + first);
        //b5fb686c5752edd1c337ac7231c6cea5
        System.out.println("第二次加密之后：" + second);
        if (second.equals(MD5Util.inputPassToDBPass(password, salt))) {
            System.out.println("密码生成正确，数据库中应该存储的 password 为=>：" + second);
        } else {
            System.out.println("密码生成错误？？？");
        }
    }
}
